const Koa = require('koa');
const Router = require('koa-router');
const cors = require('koa-cors');
const path = require('path');
const fs = require('fs');

const app = new Koa();
const router = new Router();

// CORS
app.use(cors());

// 静态文件服务 - uploads
app.use(async (ctx, next) => {
    if (ctx.path.startsWith('/uploads/')) {
        const filePath = path.join(__dirname, 'uploads', ctx.path.replace('/uploads/', ''));
        console.log('请求uploads:', filePath, '存在:', fs.existsSync(filePath));
        if (fs.existsSync(filePath)) {
            ctx.type = path.extname(filePath);
            ctx.body = fs.createReadStream(filePath);
            return;
        }
    }
    await next();
});

// 静态文件服务 - static
app.use(async (ctx, next) => {
    if (ctx.path.startsWith('/static/')) {
        const filePath = path.join(__dirname, '..', 'static', ctx.path.replace('/static/', ''));
        console.log('请求static:', filePath, '存在:', fs.existsSync(filePath));
        if (fs.existsSync(filePath)) {
            ctx.type = path.extname(filePath);
            ctx.body = fs.createReadStream(filePath);
            return;
        }
    }
    await next();
});

// 根路由
router.get('/', async (ctx) => {
    ctx.body = { message: '服务器运行中', time: new Date().toISOString() };
});

// 健康检查
router.get('/health', async (ctx) => {
    ctx.body = { status: 'ok' };
});

app.use(router.routes());
app.use(router.allowedMethods());

const PORT = 3000;
app.listen(PORT, '0.0.0.0', () => {
    console.log(`✅ 服务器启动成功: http://localhost:${PORT}`);
    console.log(`📁 静态目录: ${path.join(__dirname, '..', 'static')}`);
    console.log(`🎵 测试URL: http://localhost:${PORT}/static/brightest_star.mp3`);
});
